package com.cvticketvender;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.cvricevender.R;
import com.google.gson.Gson;

import java.io.UnsupportedEncodingException;
import java.util.Calendar;

import cv.vender.PrinterUtil;
import cv.vender.clsArgs;
import cv.vender.clsCmdConst;
import cv.vender.clsErrorConst;
import cv.vender.clsPublicPara;
import cv.vender.clsToolBox;
import cv.vender.http.bean.clsSendTradeToPc;
import cv.vender.para.clsCardSnPara;
import cv.vender.para.clsHandShakePara;
import cv.vender.para.clsPcPollCreditPara;
import cv.vender.para.clsPollTransfor;
import cv.vender.para.clsProductPara;
import cv.vender.para.clsStatisticPara;


@SuppressWarnings("WeakerAccess")
class ProductLable {
    private static final String CHAR_CODE = "GBK";
    public EditText txt_price = null;
    public EditText txt_t = null;
    public CheckBox chk_on = null;


    public clsProductPara product = null;


    public void fill(String src) {
        //System.out.println(src);
        if (src != null) {
            if (!src.equals("")) {
                try {
                    src = new String(Base64.decode(src, Base64.DEFAULT), CHAR_CODE);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                Gson g = new Gson();
                product = g.fromJson(src, clsProductPara.class);
                if (product != null) {
                    txt_price.setText(String.valueOf(product.getPrice() / 100));
                    txt_t.setText(product.getName());
                    chk_on.setChecked(product.isuse());
                }
            }
        }
    }

    public clsProductPara getProduct() {
        if (product == null) {
            product = new clsProductPara();
        }
        product.setName(txt_t.getText().toString());
        product.setPrice(clsToolBox.ParseInt(txt_price.getText().toString()) * 100);//*了一百
        product.setIsuse(chk_on.isChecked());
        return product;
    }

    public String toString() {
        Gson g = new Gson();
        String str = g.toJson(product, clsProductPara.class);
        try {
            return Base64.encodeToString(str.getBytes(CHAR_CODE), Base64.NO_WRAP);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

}

@SuppressWarnings({"FieldCanBeLocal", "JavaDoc"})
public class Main2Activity extends Activity {

    CheckBox[] chk_SelSeral = null;
    ProductLable[] productlab = null;
    Toast toast = null;
    int lBills = 0;
    int lCoins = 0;
    boolean lUseWx = false;
    boolean lUseAl = false;
    int lclick_count = 0;
    private Button butStartTransfor = null;
    private Button butEnableBills = null;
    private Button butDisableBills = null;
    private Button butGetCredit = null;
    private Button butClrCredit = null;
    private Button butHandShake = null;
    private Button butClear = null;
    private EditText txt_ret;//
    private Handler handle;
    private TextView txt_tips = null;
    private TextView txt_tips_max = null;
    private EditText txt_price = null;
    private EditText txt_venderid = null;
    private EditText txt_serverurl = null;
    //        o.setTitle(txt_shop_name.getText().toString());
    private EditText txt_shop_name = null;
    private EditText txt_WelcomTips = null;
    private SeekBar seekBar;

    public static void setVoiceVolume(Context context, int value) {
        AudioManager mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        // 注意：分为静音(0)，震动(0)，1--7 共九个等级。从静音调为1时，需要调大两个等级；从1调为0时，手机将调整为“震动模式”
        int currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        //尼玛，我获得的最大值是15
        int maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        int newVolume = currentVolume + value;
        if (newVolume > maxVolume) {
            newVolume = maxVolume;
        } else if (newVolume < 0) {
            newVolume = 0;
        }
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, newVolume, 0);
    }

    public void ShowToast(String textstr) {
        //获取LayoutInflater对象，该对象能把XML文件转换为与之一直的View对象
        LayoutInflater inflater = getLayoutInflater();
        //根据指定的布局文件创建一个具有层级关系的View对象
        //第二个参数为View对象的根节点，即LinearLayout的ID
        View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));
        //查找ImageView控件
        //注意是在layout中查找
        //ImageView image = (ImageView) layout.findViewById(R.id.image);
        //image.setImageResource(id);
        TextView text = layout.findViewById(R.id.text);
        text.setTextSize(48);
        text.setText(textstr);

        if (toast == null) {
            toast = new Toast(getApplicationContext());
        }
        //设置Toast的位置
        toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        toast.setDuration(Toast.LENGTH_LONG);
        //让Toast显示为我们自定义的样子
        toast.setView(layout);
        toast.show();
        if (txt_ret.getText().length() > 2000) {
            txt_ret.setText("");
        }
        txt_ret.append(clsToolBox.getDateTimeString() + "--" + textstr + "\r\n");
    }

    private void AppendText(String textstr) {
        txt_ret.append(clsToolBox.getDateTimeString() + "--" + textstr + "\r\n");
    }

    private void FillChkBox(int id, int val) {
        FillChkBox(id, val != 0);
    }

    private void FillChkBox(int id, boolean val) {
        try {
            CheckBox chkbox = findViewById(id);
            chkbox.setChecked(val);
        } catch (Exception e1) {
            e1.printStackTrace();
        }

    }

    @SuppressLint("HandlerLeak")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 隐藏标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main2);


        txt_ret = findViewById(R.id.txt_ret);

        //et.setKeyListener(null);
        txt_ret.setKeyListener(null);

        int i = 0;


        butStartTransfor = findViewById(R.id.butStartTransfor);
        butEnableBills = findViewById(R.id.butEnableBills);
        butDisableBills = findViewById(R.id.butDisableBills);
        butGetCredit = findViewById(R.id.butGetCredit);
        butClrCredit = findViewById(R.id.butClrCredit);
        txt_shop_name = findViewById(R.id.txt_shop_name);
        txt_WelcomTips = findViewById(R.id.txt_WelcomTips);
        butHandShake = findViewById(R.id.butHandShake);


        //txt_tips_max.setText(String.format("必须获取%d个AD值",clsCalibrationPara.COUNT+1));

        butClear = findViewById(R.id.butClear);


        txt_serverurl = findViewById(R.id.txt_serverurl);
        txt_serverurl.setText(clsArgs.getInst().getServerurl());

        txt_venderid = findViewById(R.id.txt_venderid);
        txt_venderid.setText(String.valueOf(clsArgs.getInst().getVenderid()));//机器编号
        txt_shop_name.setText(clsArgs.getInst().getTitle());
        txt_WelcomTips.setText(clsArgs.getInst().getmWelcomTips());
        seekBar = findViewById(R.id.seekBar);
        final AudioManager mAudioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
        seekBar.setMax(mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
        seekBar.setProgress(mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC));

        lUseWx = clsArgs.getInst().isUseWx();
        lUseAl = clsArgs.getInst().isUseAl();

        lBills = clsArgs.getInst().getBills();
        lCoins = clsArgs.getInst().getCoins();

        AppendText(String.format("使用微信:%s", lUseWx ? "是" : "否"));
        AppendText(String.format("使用支付宝:%s", lUseAl ? "是" : "否"));
        AppendText(String.format("纸币:%X", lBills));
        AppendText(String.format("硬币:%X", lCoins));

        FillChkBox(R.id.chk_AlEn, lUseAl);
        FillChkBox(R.id.chk_WxEn, lUseWx);

        /*coin*/
        FillChkBox(R.id.chk_cash_0, lCoins & (1 << 0));
        FillChkBox(R.id.chk_cash_1, lCoins & (1 << 1));

        /*cash*/
        FillChkBox(R.id.chk_cash_2, lBills & (1 << 0));//1元
        FillChkBox(R.id.chk_cash_3, lBills & (1 << 1));//5元
        FillChkBox(R.id.chk_cash_4, lBills & (1 << 2));//10元
        FillChkBox(R.id.chk_cash_5, lBills & (1 << 3));//20元
        FillChkBox(R.id.chk_cash_6, lBills & (1 << 4));//50元
        FillChkBox(R.id.chk_cash_7, lBills & (1 << 5));//100元


        if (productlab == null) {
            String[] contentlst = clsArgs.getInst().getProduct();

            //从文件中读取数据

            productlab = new ProductLable[4];
            i = 0;
            productlab[i] = new ProductLable();
            productlab[i].txt_t = findViewById(R.id.txt_t1);
            productlab[i].txt_price = findViewById(R.id.txt_price1);
            productlab[i].chk_on = findViewById(R.id.chk_on1);
            productlab[i].fill(contentlst[i]);
            i++;
            productlab[i] = new ProductLable();
            productlab[i].txt_t = findViewById(R.id.txt_t2);
            productlab[i].txt_price = findViewById(R.id.txt_price2);
            productlab[i].chk_on = findViewById(R.id.chk_on2);
            productlab[i].fill(contentlst[i]);
            i++;
            productlab[i] = new ProductLable();
            productlab[i].txt_t = findViewById(R.id.txt_t3);
            productlab[i].txt_price = findViewById(R.id.txt_price3);
            productlab[i].chk_on = findViewById(R.id.chk_on3);
            productlab[i].fill(contentlst[i]);
            i++;
            productlab[i] = new ProductLable();
            productlab[i].txt_t = findViewById(R.id.txt_t4);
            productlab[i].txt_price = findViewById(R.id.txt_price4);
            productlab[i].chk_on = findViewById(R.id.chk_on4);
            productlab[i].fill(contentlst[i]);
        }


        chk_SelSeral = new CheckBox[4];
        i = 0;
        chk_SelSeral[i++] = findViewById(R.id.chk_serial0);
        chk_SelSeral[i++] = findViewById(R.id.chk_serial1);
        chk_SelSeral[i++] = findViewById(R.id.chk_serial2);
        chk_SelSeral[i++] = findViewById(R.id.chk_serial3);

        String select_port = clsArgs.getInst().getCommid();

        for (i = 0; i < chk_SelSeral.length; i++) {
            chk_SelSeral[i].setTag("/dev/ttyS" + i);
            chk_SelSeral[i].setChecked(select_port.equals("/dev/ttyS" + i));
        }

        //音量调节
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, i, 0);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        handle = new Handler() {
            @SuppressLint("DefaultLocale")
            @Override
            public void handleMessage(Message msg) {
                try {
                    switch (msg.what) {
                        case clsCmdConst.CMD_OPEN_SERIAL_PORT:
                            break;
                        case clsCmdConst.CMD_PC_LNK://butHandShake
                            clsHandShakePara handShakePara = (clsHandShakePara) msg.obj;
                            if (msg.arg1 == clsErrorConst.MDB_ERR_NO_ERR) {
                                ShowToast(String.format("握手成功，程序版本号%X", handShakePara.getVer()));
                            } else {
                                ShowToast(String.format("握手失败,故障码%d", msg.arg1));
                            }
                            break;
                        case clsCmdConst.CMD_PC_POLL:

                            break;
                        case clsCmdConst.CMD_PC_CREDIT:
                            clsPcPollCreditPara PcPollCreditPara = (clsPcPollCreditPara) msg.obj;
                            if (msg.arg1 == clsErrorConst.MDB_ERR_NO_ERR) {
                                ShowToast(String.format("获取投入金额：%d分", PcPollCreditPara.getCredit()));
                            } else {
                                ShowToast(String.format("获取投入金额失败,故障码%d", msg.arg1));
                            }
                            break;
                        case clsCmdConst.CMD_PC_MDB_CLEAR_CREDIT:
                            clsPcPollCreditPara PcPollCreditPara2 = (clsPcPollCreditPara) msg.obj;
                            if (msg.arg1 == clsErrorConst.MDB_ERR_NO_ERR) {
                                ShowToast(String.format("获取投入金额：%d分，总金额清0", PcPollCreditPara2.getCredit()));
                            } else {
                                ShowToast(String.format("获取投入金额失败,总金额清0失败,故障码%d", msg.arg1));
                            }
                            break;
                        case clsCmdConst.CMD_PC_TRANSFOR:
                            if (msg.arg1 == clsErrorConst.MDB_ERR_NO_ERR) {
                                ShowToast("出货指令发送成功");
                                ThreadForBrd.getInstence().SendPollTransforRequest();
                            } else {
                                ShowToast(String.format("出货指令发送失败,故障码%d", msg.arg1));
                            }
                            break;
                        case clsCmdConst.CMD_PC_POLL_TRANSFOR:
                            clsPollTransfor pollTransfor = (clsPollTransfor) msg.obj;
                            if (pollTransfor != null) {

                                if (msg.arg1 == clsErrorConst.MDB_ERR_NO_ERR) {
                                    int state = pollTransfor.getState();
                                    if (state == clsPollTransfor.STATE_TRANSFORING) {
                                        ShowToast(String.format("还正在出米,已出米%dg,状态：%d", pollTransfor.getOutRice(), state));
                                        ThreadForBrd.getInstence().SendPollTransforRequest();
                                    } else if (state == clsPollTransfor.STATE_TRANSFORED) {
                                        ShowToast(String.format("出米完成,共出米%dg,状态：%d", pollTransfor.getOutRice(), state));
                                    } else if (state == clsPollTransfor.STATE_TRANSFOR_PAUSE) {
                                        ShowToast(String.format("还正在出米,已出米%dg,状态：%d,暂停中", pollTransfor.getOutRice(), state));
                                        ThreadForBrd.getInstence().SendPollTransforRequest();
                                    } else if (state == clsPollTransfor.STATE_TRANSFOR_FAIL) {
                                        ShowToast(String.format("出米失败,已出米%dg,状态：%d,暂停中", pollTransfor.getOutRice(), state));
                                    } else {

                                    }
                                } else {
                                    ShowToast(String.format("查询出货指令发送失败,故障码%d", msg.arg1));
                                }
                            }
                            break;
                        case clsCmdConst.CMD_PC_SET_BILL_TYPE:
                            if (msg.arg1 == clsErrorConst.MDB_ERR_NO_ERR) {
                                ShowToast("设置钱币使能成功");
                            } else {
                                ShowToast(String.format("设置钱币使能失败,故障码%d", msg.arg1));
                            }
                            break;
                        case clsCmdConst.CMD_PC_READ_ADC:
                            break;
                        case clsCmdConst.CMD_PC_GET_CARDSN: {
                            clsCardSnPara cardSnPara = (clsCardSnPara) msg.obj;
                            if (msg.arg1 == clsErrorConst.MDB_ERR_NO_ERR) {
                                if (cardSnPara.isSuccess()) {
                                    ShowToast("获取卡号成功，卡号：" + cardSnPara.getCardSn());
                                } else {
                                    ShowToast("未查找到卡片");
                                }
                            } else {
                                ShowToast(String.format("获取卡号失败,故障码%d", msg.arg1));
                            }
                        }
                        default:
                            break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        ThreadForBrd.getInstence().toSetState(handle);
        butStartTransfor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clsSendTradeToPc tradeToPc = new clsSendTradeToPc();
                tradeToPc.setTradeId("12345678");
                tradeToPc.setDatetime(Calendar.getInstance());
                PrinterUtil.getInst().PrintContent(tradeToPc);
            }
        });


        butClrCredit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                clsStatisticPara sPara = new clsStatisticPara();

                sPara.setT_tradecount(clsPublicPara.XuhaoPara.getTotal().getBishu());
                sPara.setT_tradebill(clsPublicPara.XuhaoPara.getTotal().getJine());
                sPara.setT_ca_tradecount(clsPublicPara.XuhaoPara.getCash().getBishu());
                sPara.setT_ca_tradebill(clsPublicPara.XuhaoPara.getCash().getJine());
                sPara.setT_wx_tradecount(clsPublicPara.XuhaoPara.getWeixin().getBishu());
                sPara.setT_wx_tradebill(clsPublicPara.XuhaoPara.getWeixin().getJine());
                sPara.setT_al_tradecount(clsPublicPara.XuhaoPara.getAlipay().getBishu());
                sPara.setT_al_tradebill(clsPublicPara.XuhaoPara.getAlipay().getJine());
                Calendar c = Calendar.getInstance();
                c.setTimeInMillis(clsPublicPara.XuhaoPara.getStart_timestamp());
                sPara.setLasttime(c);
                //clsArgs ins= clsArgs.getInst();
                //ins.readStatistic(sPara);
                PrinterUtil.getInst().PrintTradeStatistic(sPara);

                clsPublicPara.XuhaoPara.Clr();
                //// TODO: 2018/1/28 添加统计小票打印功能

                ThreadForBrd.getInstence().SetTradeMsg(clsPublicPara.XuhaoPara);

            }
        });

        butDisableBills.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ThreadForBrd.getInstence().SetCashType(0, 0);
            }
        });


        butEnableBills.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ThreadForBrd.getInstence().SetCashType(0xffff, 0xffff);
            }
        });

        butGetCredit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ThreadForBrd.getInstence().StartCreditPoll();
            }
        });


        butHandShake.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //// TODO: 2016-12-30 butHandShake
                clsHandShakePara para = new clsHandShakePara();
                Message msg = null;
                msg = ThreadForBrd.getInstence().
                        getmChildHandler().
                        obtainMessage(clsCmdConst.CMD_PC_LNK, para);
                msg.sendToTarget();
            }
        });

        butClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                txt_ret.setText("");
            }
        });
    }

    /**
     * 关闭设置
     *
     * @param View
     */
    public void Click_Exit(View View) {
        ThreadForBrd.getInstence().toDefaultState();
        System.exit(0);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
        }
        return false;
    }


    /**
     * 点击保存所有
     *
     * @param view
     */
    public void btnSave_onClick(View view) {
        clsArgs o = clsArgs.getInst();
        //int price=clsToolBox.ParseInt(txt_price.getText().toString());
        String[] plst = o.getProduct();

        int i;
        for (i = 0; i < productlab.length; i++) {
            productlab[i].getProduct().setId(i + 1);

            plst[i] = productlab[i].toString();
        }
        /*保存串口*/
        for (i = 0; i < chk_SelSeral.length; i++) {
            if (chk_SelSeral[i].isChecked()) {
                clsArgs.getInst().setCommid((String) chk_SelSeral[i].getTag());
            }
        }

        String url = txt_serverurl.getText().toString().trim();
        o.setServerurl(url);
        int vid = clsToolBox.ParseInt(txt_venderid.getText().toString());
        o.setVenderid(vid);

        o.setBills(lBills);
        o.setCoins(lCoins);
        //AppendText(String.format("%X",lCoins));

        o.setUseAl(lUseAl);
        o.setUseWx(lUseWx);
        o.setTitle(txt_shop_name.getText().toString());
        o.setmWelcomTips(txt_WelcomTips.getText().toString());
        //保存配置文件
        clsArgs.getInst().SavePara();
        ShowToast("保存成功");
    }

    public void btn_onClick(View view) {
        ThreadForBrd.getInstence().StartGetCardSn();
    }


    /**
     * 退出程序
     *
     * @param view
     */
    public void btnShoutdown_onClick(View view) {
        //android.os.Process.killProcess(android.os.Process.myPid());    //获取PID

        Intent intent = new Intent(this, Main2Activity.class);
        intent.putExtra("isExist", true);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);

        this.startActivity(intent);

        System.exit(0);   //常规java、c#的标准退出法，返回值为0代表正常退出

    }


    /**
     * 启动更新
     *
     * @param view
     */
    public void btnupdate_onClick(View view) {
        Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.example.appupdatedemo");
        startActivity(LaunchIntent);
    }

    int SetBits(int mNo, int mPos) {
        return mNo | (1 << mPos);
    }

    int ResetBits(int mNo, int mPos) {
        return mNo & (~(1 << mPos));
    }

    public void ChkBill_OnClick(View view) {
        CheckBox chkbox = (CheckBox) view;
        int mTem = 0;
        switch (chkbox.getId()) {
            case R.id.chk_cash_2:
                mTem = 0;
                break;
            case R.id.chk_cash_3:
                mTem = 1;
                break;
            case R.id.chk_cash_4:
                mTem = 2;
                break;
            case R.id.chk_cash_5:
                mTem = 3;
                break;
            case R.id.chk_cash_6:
                mTem = 4;
                break;
            case R.id.chk_cash_7:
                mTem = 5;
                break;
        }
        lBills = (chkbox.isChecked()) ? SetBits(lBills, mTem) : ResetBits(lBills, mTem);

    }

    public void ChkCoin_OnClick(View view) {
        CheckBox chkbox = (CheckBox) view;
        int mTem = 0;
        switch (chkbox.getId()) {
            case R.id.chk_cash_0:
                mTem = 0;
                break;
            case R.id.chk_cash_1:
                mTem = 1;
                break;
        }
        lCoins = (chkbox.isChecked()) ? SetBits(lCoins, mTem) : ResetBits(lCoins, mTem);

    }

    public void ChkWxEn_OnClick(View view) {
        CheckBox chkbox = (CheckBox) view;

        lUseWx = chkbox.isChecked();
    }

    public void ChkAlEn_OnClick(View view) {
        CheckBox chkbox = (CheckBox) view;
        lUseAl = chkbox.isChecked();
    }

    public void chk_serial_OnClick(View view) {
        int i = 0;
        for (i = 0; i < chk_SelSeral.length; i++) {
            chk_SelSeral[i].setChecked(false);
        }
        ((CheckBox) view).setChecked(true);
    }

    public void Click_SetSelectPortEn(View view) {
        if (lclick_count++ > 4) {
            int i = 0;
            for (i = 0; i < chk_SelSeral.length; i++) {
                chk_SelSeral[i].setEnabled(true);
            }
        }
    }
}
